ProbabilitiesManager = class("ProbabilitiesManager")

require("LocalisationRules")
require("EntityPropertiesPostCollapseRules")
require("PruningRules")

---

function ProbabilitiesManager:initialize()

	self:createStaticAndDynamicVersionOfSomePropertiesProbabilities()	
	self:calculateLocationsDistances()
	self:moveKeysAwayFromDoors()	
end

---

function ProbabilitiesManager:onBeatBeforeField()

	self:moveKeysAwayFromPlayer()	
	self:mergeStaticAndDynamicVersionOfSomePropertiesProbabilities()	
end

---

function ProbabilitiesManager:onBeatAfterField()

	self:pruneUselessKeys()
end

---

function ProbabilitiesManager:createStaticAndDynamicVersionOfSomePropertiesProbabilities()

	if gField.entityTypes.Key
	then
		for keyName, key in pairs(gField.entityTypes.Key) do
		
			key.locationStaticProbabilities = {}
			key.locationDynamicProbabilities = {}
			
			for possibleLocation, probability in pairs(key.CurrentContainer) do
			
				key.locationStaticProbabilities[possibleLocation] = probability
				key.locationDynamicProbabilities[possibleLocation] = 0
			end	
		end
	end
end

---

function ProbabilitiesManager:mergeStaticAndDynamicVersionOfSomePropertiesProbabilities()

	if gField.entityTypes.Key
	then
		for keyName, key in pairs(gField.entityTypes.Key) 
		do
			for possibleLocation, probability in pairs(key.CurrentContainer) 
			do
				local staticProbability = key.locationStaticProbabilities[possibleLocation]
				if not staticProbability 
				then
					staticProbability = 1
				end
				
				local dynamicProbability = key.locationDynamicProbabilities[possibleLocation]
				if not dynamicProbability 
				then
					dynamicProbability = 0
				end
				
				key.CurrentContainer[possibleLocation] = staticProbability + dynamicProbability
			end	
		end
	end
end
---

function ProbabilitiesManager:calculateLocationsDistances()

	for locationName, location in pairs(gField.entityTypes.Location) 
	do
		location.distanceToOtherLocations = {}
		
		self:setLocationDistance(location, location, 0)
	end
end

---

function ProbabilitiesManager:setLocationDistance(location, connectedLocation, distance)

	if not location.distanceToOtherLocations[connectedLocation] 
	then
		location.distanceToOtherLocations[connectedLocation] = distance
		
		--print ("location " .. location.name .. " distance from " .. connectedLocation.name .. " is " .. distance)
		
		for doorName, door in pairs(connectedLocation:getDoors(true)) 
		do
			self:setLocationDistance(location, door:getOtherSide(connectedLocation), distance + 1)
		end
	end
end

